<?php 
use \PsiFramework\Classes\Util\UI\Printer;
use \PsiFramework\Classes\Util\UI\HTML;

$user = $response->getAttribute("user");
if (is_null($user)) $user = $response->getAttribute("object");

$action = $response->getAttribute("action");
if (is_null($action)) $action = "CMS.Save" ;

$captcha = $response->getAttribute("captcha");
$error = $response->getAttribute("error");
$lang = $response->getAttribute("lang");
$div = strtolower($action);

$objectType = $response->getAttribute("objectType");

$reqParams = "action=" . $action ;
if (!is_null($objectType)) $reqParams .= "&type=" . $objectType ;

$adminChecked = '' ;
$userChecked = '' ;
if (!is_null($user)) {
    $roles = $user->getRoles();
    if (!is_null($roles)) {
        foreach ($roles as $role) {
            $roleName = $role->getRole()->getName();
            if ($roleName == 'allomedia_user') {
                $userChecked = 'checked="checked"' ;
            }
            if ($roleName == 'allomedia_admin') {
                $adminChecked = 'checked="checked"' ;
            }
        }
    }
} else {
    $userChecked = 'checked="checked"' ;
}

?>
<div id="<?php Printer::display($div); ?>">
    <?php
    if ($error != null) {
    ?>
    <div id="formError" class="error">
        <?php Printer::display($error);?>
    </div>
    <?php 
    }
    ?>
    <form
        class="editForm"
        id="userForm"
        action="<?php Printer::display(HTML::linkHref($reqParams));?>"
        method="POST"
        enctype="multipart/form-data">
        <input type="hidden" name="redirectAction" value="Profile" />
        <?php
        if ($user!=null && $user->getId() != null) {
        ?>
        <input
            type="hidden"
            id="user_id"
            name="id"
            value="<?php Printer::display($user->getId()); ?>" />
        <?php
        }
        ?>
        <div class="label oblig">
            <span class="titre">
                <?php Printer::display($languageManager->getText("LOGIN_NAME")); ?> :
            </span>
            <input
                class="firstInput unique required"
                type="text"
                name="login" id="loginBox"
                value="<?php if ($user!=null && $user->getLogin() != null) Printer::display($user->getLogin()); ?>"
                required="required" />
        </div>
        <div class="label oblig">
            <span class="titre">
                <?php Printer::display($languageManager->getText("EMAIL")); ?> :
            </span>
            <input
                class="firstInput unique email required"
                type="email"
                name="email"
                id="emailBox"
                value="<?php if ($user!=null && $user->getEmail() != null) Printer::display($user->getEmail()); ?>"
                required="required" />
        </div>
        <div class="label oblig">
            <span class="titre">
                Role :
            </span>
            <label>
                <input
                    type="checkbox"
                    name="role[]"
                    value="allomedia_user" <?php echo $userChecked ; ?> />
                    Utilisateur
            </label>
            <label>
                <input
                    type="checkbox"
                    name="role[]"
                    value="allomedia_admin" <?php echo $adminChecked ; ?> />
                    Admin
            </label>
        </div>
        <?php 
        if (!is_null($user)) {
        ?>
        <div class="label oblig">
            <span class="titre">Créer une fiche : </span>
            <label>
                Site :
                <input
                    type="text"
                    id="site"
                    value="" />
                <input
                    type="hidden"
                    id="site_id"
                    value="" />
            </label>
            <label>
                Id de la fiche sur le site :
                <input
                    type="text"
                    id="entry"
                    size="1"
                    value="" />
            </label>
            <input
                type="button"
                value="Créer la fiche"
                onclick="javascript:createEntry()" />
            <span id="importMessage"></span>
        </div>
        <div class="label">
            <input
                type="button"
                onClick="javascript:sendNewPassword()"
                value="Envoyer un nouveau mot de passe" />
        </div>
        <?php 
        }
        ?>
        <input
            type="submit"
            value="<?php Printer::display($languageManager->getText("SUBMIT")); ?>" />
    </form>
</div>
<script type="text/javascript">

    $(document).ready(function() {
        $.validator.addMethod("unique", function(value, element) {
            var response = false ;
            var user = $("#user_id").val();
            if (user == undefined) user = '' ;
                
            $.ajax({
                async: false,
                type: "POST",
                url: "?service=CheckUserUnicity",
                data: element.name+"="+value+"&user_id="+user,
                dataType:"json",
                success: function(json)
                {
                  //If username exists, set response to true
                  response = !json.exists ;
                }
            })
            return response ;
        }, "Valeur déjà présente en base !");
        $("#userForm").validate();
    });

    $("#site").autocomplete({
        source: "?service=ListSites&format=json",
        select: function(event, ui) {
            $("#site").val(ui.item.label);
            $("#site_id").val(ui.item.id);
        }
    });

    function createEntry() {
        var user = $("#user_id").val();
        var site = $("#site_id").val();
        var idOnSite = $("#entry").val();

        if (site==null || site=='' || idOnSite==null || idOnSite=='') {
            alert("Veuillez entrer un site valide et un identifiant !");
            return ;
        }
        
        var url = "?service=CreateEntry&user_id=" + user +
                      "&site_id=" + site + "&id_on_site=" + idOnSite ;
        $.ajax({
            url: url,
            type: 'GET',
            cache: false,
            timeout: 60000,
            beforeSend: function() {
                $('#importMessage').html('en cours de récupération...')
            },
            complete: function() {
                $('#importMessage').html('');
            },
            error: function() {
                alert('Erreur lors de la création !');
            },
            success: function(data) { 
                var id = parseInt(data);
                if (isNaN(id)) {
                    alert('Erreur lors de la récupération de l\'entrée ! Vérifiez le service !');
                }
                else {
                    window.location.href="?application=AlloMediaAdmin&action=CMS.Show&type=AlloMediaEntry&id="+id;
                }
            }
        });
    }

    function sendNewPassword() {
        var user = $("#user_id").val();
        if (user == undefined) {
             alert('Identifiant non valide !');
        }
        else{
            var url = "?service=SendNewPassword&user_id=" + user ;
            $.ajax({
                url: url,
                type: 'GET',
                cache: false,
                timeout: 60000,
                beforeSend: function() {
                    $('#importMessage').html('En cours d\'envoi...')
                },
                complete: function() {
                    $('#importMessage').html('');
                },
                error: function() {
                    alert('Erreur lors de l\'envoi !');
                },
                success: function(data) { 
                    if (data != 'ok') {
                        alert('Erreur lors de l\'envoi du nouveau mot de passe !');
                    }
                    else {
                        alert('Nouveau mot de passe envoyé !');
                    }
                }
            });
        }
    }
    
</script>
